import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:nyh_motorcade_app/styles/colors.dart';
import 'package:nyh_motorcade_app/utils/system_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class UpdateAppDialog extends StatefulWidget {
  final String urlPath;
  final String title;
  final String contentTitle;
  final String? content;
  final String cancelText;
  final String confirmText;
  final bool isForceUpdate;

  UpdateAppDialog({
    Key? key,
    required this.urlPath,
    this.title = "新版本升级",
    this.contentTitle = "更新内容",
    this.content = "",
    this.cancelText = "下次更新",
    this.confirmText = "立即更新",
    this.isForceUpdate = false,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _UpdateAppDialogState();
  }
}

class _UpdateAppDialogState extends State<UpdateAppDialog> {
  bool isDownloading = false;
  double downloadProgress = 0;

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: Container(
          margin: EdgeInsets.symmetric(vertical: 0, horizontal: 30.w),
          padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 16.w),
          decoration: BoxDecoration(
            color: Colours.color_white,
            borderRadius: BorderRadius.all(
              Radius.circular(5.w),
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Center(
                child: Text(
                  widget.title,
                  style: TextStyle(
                    color: Colours.color_text_theme,
                    fontSize: 18.sp,
                  ),
                ),
              ),
              SizedBox(
                height: 20.w,
              ),
              Text(
                widget.contentTitle,
                style: TextStyle(
                  color: Colours.color_text_theme,
                  fontSize: 14.sp,
                ),
              ),
              SizedBox(
                height: 5.w,
              ),
              Text(
                getContent() ?? "",
                style: TextStyle(
                  color: Colours.color_666666,
                  fontSize: 14.sp,
                  height: 2,
                ),
              ),
              SizedBox(
                height: 30.w,
              ),
              Visibility(
                visible: !isDownloading,
                child: Row(
                  children: [
                    Visibility(
                      visible: !widget.isForceUpdate,
                      child: Expanded(
                        child: TextButton(
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          style: ButtonStyle(
                            padding: MaterialStateProperty.all(
                              EdgeInsets.only(top: 9.w, bottom: 9.w),
                            ),
                            backgroundColor: MaterialStateProperty.all(Colours.color_white),
                            shape: MaterialStateProperty.all(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(20.w),
                                side: BorderSide(width: 1, color: Colours.color_theme),
                              ),
                            ),
                          ),
                          child: Text(
                            widget.cancelText,
                            style: TextStyle(
                              color: Colours.color_theme,
                              fontSize: 16.sp,
                            ),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: widget.isForceUpdate ? 0 : 15.w),
                    Expanded(
                      child: TextButton(
                        onPressed: () {
                          if (widget.urlPath.isEmpty) {
                            ToastUtils.toast("url为空");
                            Navigator.pop(context);
                            return;
                          }
                          if (Platform.isAndroid) {
                            download(context);
                          } else if (Platform.isIOS) {
                            goToAppStore();
                          }
                        },
                        style: ButtonStyle(
                          padding: MaterialStateProperty.all(
                            EdgeInsets.only(top: 9.w, bottom: 9.w),
                          ),
                          backgroundColor: MaterialStateProperty.all(Colours.color_theme),
                          shape: MaterialStateProperty.all(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20.w),
                            ),
                          ),
                          overlayColor: MaterialStateProperty.all(Colours.color_theme_deep),
                        ),
                        child: Text(
                          widget.confirmText,
                          style: TextStyle(
                            color: Colours.color_white,
                            fontSize: 16.sp,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Visibility(
                visible: isDownloading,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(3.w)),
                      child: SizedBox(
                        width: double.infinity,
                        height: 3.w,
                        child: LinearProgressIndicator(
                          backgroundColor: Colours.color_d8d8d8,
                          value: downloadProgress,
                          valueColor: AlwaysStoppedAnimation<Color>(Colours.color_theme),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 5.w,
                    ),
                    Text(
                      "${(downloadProgress * 100).toStringAsFixed(2)}%",
                      style: TextStyle(color: Colours.color_text_theme, fontSize: 12.sp),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  String? getContent() {
    if (widget.content == null || widget.content!.isEmpty) {
      return "";
    }
    if (widget.content!.contains("\\n")) {
      return widget.content!.replaceAll("\\n", "\n");
    }
    return widget.content;
  }

  Future<void> download(BuildContext context) async {
    PermissionStatus status = await Permission.storage.request();
    if (status != PermissionStatus.granted) {
      ToastUtils.toast("请打开读写手机存储权限");
      Navigator.pop(context);
      return;
    }

    Directory? directory = await getExternalStorageDirectory();
    if (directory == null || directory.path.isEmpty) {
      ToastUtils.toast("获取存储路径失败");
      Navigator.pop(context);
      return;
    }
    String savePath = directory.path + "/operate.apk";

    try {
      Dio dio = Dio();
      Response response = await dio.download(widget.urlPath, savePath, onReceiveProgress: (count, total) {
        if (total != -1) {
          if (mounted) {
            setState(() {
              isDownloading = true;
              downloadProgress = (count / total);
              print("下载进度:" + (downloadProgress * 100).toStringAsFixed(2) + "%");
            });
          }
        }
      });
      if (response.statusCode == 200) {
        print("下载成功,路径:$savePath");
        String packageName = await SystemUtils.getPackageName();
        InstallPlugin.installApk(savePath, packageName);
        Navigator.pop(context);
      } else {
        ToastUtils.toast("下载失败");
        Navigator.pop(context);
      }
    } catch (e) {
      ToastUtils.toast("下载异常");
      Navigator.pop(context);
    }
  }

  void goToAppStore() {
    InstallPlugin.gotoAppStore(widget.urlPath);
  }
}
